import pygame
from pygame.locals import *

#初始化
pygame.init()

#窗口大小
size = width, height = 480, 480
#初始化一个准备显示的窗口
screen = pygame.display.set_mode(size)
#创建一个对象来帮助跟踪时间
clock = pygame.time.Clock()
#颜色
black, red, blue, white = (0, 0, 0), (255, 0, 0), (0, 0, 255), (255, 255, 255)
#创建列表储存落子情况
empty, x, o = 0, 1, 2
board = [[empty] * 3, [empty] * 3, [empty] * 3]
#测试
board[1][1] = 1
board[0][1] = 2
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit(0)
    #pygame.draw  绘制图形模块rect()绘制矩形line()绘制线段。具体看Pygame文档。
    pygame.draw.rect(screen, white, (0, 0, width, height))
    pygame.draw.line(screen, black, (160, 0), (160, 480), 5)
    pygame.draw.line(screen, black, (320, 0), (320, 480), 5)
    pygame.draw.line(screen, black, (0, 160), (480, 160), 5)
    pygame.draw.line(screen, black, (0, 320), (480, 320), 5)


    #遍历棋盘确定位置
    for row, line in enumerate(board):
        for col, val in enumerate(line):
            if val == x:
                #绘制X
                upper_left = (col * 160 + 5, row * 160 + 5)
                lower_right = (col * 160 + 155, row * 160 + 155)
                pygame.draw.line(screen, red, upper_left, lower_right, 5)
                upper_right = (col * 160 + 155, row * 160 + 5)
                lower_left = (col * 160 + 5, row * 160 + 155)
                pygame.draw.line(screen, red, upper_right, lower_left, 5)
            elif val == o:
                #绘制O
                rect = (col * 160 + 5, row * 160 + 5, 150, 150)
                pygame.draw.ellipse(screen, blue, rect, 5)
            else:
                assert val == empty
                continue
    
    #游戏最大帧率60
    clock.tick(60)
    #刷新
    pygame.display.flip()
